package com.ztmg.water.controller.file;

import com.ztmg.common.constant.CommonConstants;
import com.ztmg.common.util.DateUtil;
import com.ztmg.common.util.RandomUtil;
import com.ztmg.common.util.resultUtils.JsonResult;
import com.ztmg.water.service.file.FileService;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FileUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping(value = "/file")
public class FileController {
    @Resource
    private FileService   fileService;

    @Value(value="${web.upload-path}")
    private String dest;
    @GetMapping("getAllImageName")
    @ApiOperation("获取图片库的所有文件名称")
    public JsonResult getAllImageName(){
        return fileService.getAllImageName(dest);

    }
    @PostMapping("deleteFile")
    @ApiOperation("获取图片库的所有文件名称")
    public JsonResult deleteFile(@RequestBody List<String> fileNames){
        StringBuilder success = new StringBuilder();
        StringBuilder exp = new StringBuilder();
        StringBuilder notFind = new StringBuilder();
        StringBuilder system = new StringBuilder();
       for (int i=0;i<fileNames.size();i++)
       {
           int resultFlag = com.ztmg.common.staticRecourse.FileUtils.deleteFile(dest+fileNames.get(i));
           switch (resultFlag)
           {
               case 0:
                   success.append(fileNames.get(i)).append(",") ;
                   break;
               case 1:
                   exp.append(fileNames.get(i)).append(",") ;
                   break;
               case 2:
                   notFind.append(fileNames.get(i)).append(",") ;
                   break;
               default:
                   system.append(fileNames.get(i)).append(",") ;
                   break;
           }

       }
        if(success.length()>0)
        {
            success=  success.delete(success.length()-1,success.length());
        }
        if(exp.length()>0){
            exp=  exp.delete(exp.length()-1,exp.length());
        }
        if(notFind.length()>0){
            notFind=  notFind.delete(notFind.length()-1,notFind.length());
        }
        if(system.length()>0){
            system=  system.delete(system.length()-1,system.length());
        }
        String resultString =  "成功删除的："+success.toString()+"，删除失败的："+exp.toString()+"，未找到的："+ notFind.toString()+"，系统错误的："+system.toString()+"。";
        return JsonResult.success(resultString);
    }
    @PostMapping("generateImage")
    @ApiOperation("生成二维码图片")
    public JsonResult generateImage(@RequestBody  List<Integer> ids){
        return fileService.generateImage(ids);
    }
    @GetMapping("generateExcel")
    @ApiOperation("生成二维码图片")
    public ResponseEntity<byte[]> generateExcel(@RequestParam  String ids)throws IOException {
        //封装http头部信息
        HSSFWorkbook wb = fileService.generateExcel(ids);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment",DateUtil.parseDateToStr(new Date(),"yyyyMMddHHmmss")+RandomUtil.getRandom(4) +".xls" );

        ByteArrayOutputStream os = new ByteArrayOutputStream();
        wb.write(os);
        return new ResponseEntity<byte[]>(os.toByteArray(), headers, HttpStatus.CREATED);
    }
    @PostMapping("upload")
    public JsonResult upload(@RequestParam("file") MultipartFile file){
        if (!file.isEmpty()) {
//            File dest = new File("E:/project1/img/", time + "_" + file.getOriginalFilename());
            try{
                com.ztmg.common.staticRecourse.FileUtils.copyInputStreamToFile(file.getInputStream(), file.getOriginalFilename(),dest);
            }
              catch (IOException e) {
                  return JsonResult.fail("文件处理失败！");
              }
            catch (Exception e) {
                return JsonResult.fail("文件处理失败！");
            }

        }
        return JsonResult.success();
    }



    @RequestMapping("download") public ResponseEntity<byte[]> download() throws IOException {
        String filename = "myTest.zip";
        File file = new File(CommonConstants.QRCODE_GENERAL_ZIP_URL);
        //封装http头部信息
         HttpHeaders headers = new HttpHeaders();
         headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
         headers.setContentDispositionFormData("attachment", filename);
         return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);
         }



}
